package com.example.springdemo.interceptor;

import com.example.springdemo.annotation.RestResponse;
import com.example.springdemo.handlers.ResHandler;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * RestResponseInterceptor
 *
 * @author wenguang
 * @date 2021/11/15 16:17
 */
@Component
public class RestResponseInterceptor implements HandlerInterceptor, Ordered {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Method method = ((HandlerMethod) handler).getMethod();
            final Class<?> beanType = handlerMethod.getBeanType();

            if (beanType.isAnnotationPresent(RestResponse.class)) {
                request.setAttribute(ResHandler.RESPONSE_RESULT_KEY, beanType.getAnnotation(RestResponse.class));
            } else if (method.isAnnotationPresent(RestResponse.class)) {
                request.setAttribute(ResHandler.RESPONSE_RESULT_KEY, method.getAnnotation(RestResponse.class));
            }
        }

        return true;
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

}
